package org.example.journal_items.controller;

import org.example.journal_items.common.Result;
import org.example.journal_items.Entity.User;
import org.example.journal_items.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.example.journal_items.utils.JwtUtil;

@RestController
@RequestMapping("/user")
public class UserController {

  @Autowired
  private UserService userService;

  @Autowired
  private JwtUtil jwtUtil;

  @PostMapping("/login")
  public Result login(@RequestBody User user) {
    return userService.login(user.getUsername(), user.getPassword());
  }

  @PostMapping("/register")
  public Result register(@RequestBody User user) {
    return userService.register(user);
  }

  @GetMapping("/check-username")
  public Result checkUsername(@RequestParam String username) {
    return userService.checkUsername(username);
  }

  @GetMapping("/info")
  public Result<User> getUserInfo(HttpServletRequest request) {
    Long userId = jwtUtil.getUserIdFromRequest(request);
    User user = userService.getUserById(userId);
    return Result.success(user);
  }

  @PostMapping("/avatar")
  public Result<String> updateAvatar(@RequestBody User user, HttpServletRequest request) {
    Long userId = jwtUtil.getUserIdFromRequest(request);
    String avatar = user.getAvatar();
    userService.updateAvatar(userId, avatar);
    return Result.success(avatar);
  }

  @PostMapping("/upload-avatar")
  public Result<String> uploadAvatar(@RequestParam("avatar") MultipartFile file, HttpServletRequest request) {
    Long userId = jwtUtil.getUserIdFromRequest(request);
    try {
      String avatar = userService.uploadAvatar(userId, file);
      return Result.success(avatar);
    } catch (Exception e) {
      return Result.error("头像上传失败: " + e.getMessage());
    }
  }

  @PutMapping("/info")
  public Result updateUserInfo(@RequestBody User user, HttpServletRequest request) {
    Long userId = jwtUtil.getUserIdFromRequest(request);
    user.setId(userId);
    String username = jwtUtil.getUsernameFromRequest(request);
    user.setUsername(username);
    return userService.updateUserInfo(user);
  }

  @PostMapping("/logout")
  public Result logout() {
    return userService.logout();
  }

  @GetMapping("/theme")
  public Result<String> getUserTheme(HttpServletRequest request) {
    Long userId = jwtUtil.getUserIdFromRequest(request);
    String theme = userService.getUserTheme(userId);
    return Result.success(theme);
  }

  @PutMapping("/theme")
  public Result updateUserTheme(@RequestBody User user, HttpServletRequest request) {
    Long userId = jwtUtil.getUserIdFromRequest(request);
    String theme = user.getTheme();
    return userService.updateUserTheme(userId, theme);
  }
}